/**
 * 
 */

var paramObj = {};
var pageCtr = 0;
var allowNext = true;
var continueBtn = "<a href=\"javascript:gotoRegistrationNextStep('register')\">Continue</a>";
var printBtn = "<a href=\"javascript:gotoRegistrationNextStep('register')\">Print</a>";
var backBtn = "<a href=\"javascript:gotoRegistrationNextStep('register')\">Review</a>";
var requiredMsg = "This field is required.";

var printBtn2 = "<a href=\"javascript:goPrintRegister()\">Print</a>";
var toRegBtn = "<a href=\"register.php\">Continue</a>";

function goUpdateRegister(newURL, type)
{
	showPreloader(true);
	allowNext = true;
	paramObj.store_cash = "";
	paramObj.store_code = $("#regMainContainer").find( 'input[name="storeCode"]' ).val();
	paramObj.register_type = type;
	
	if(type == "open")
	{
		paramObj.store_cash = $("#regMainContainer").find( 'input[name="storeCash"]' ).val();
		if(paramObj.store_cash == "")
		{
			allowNext = false;
			$("#storeCashErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#storeCashErrorMsg").empty().append( "" );
	}
	
	if(paramObj.store_user == "")
	{
		allowNext = false;
		$("#storeCodeErrorMsg").empty().append( requiredMsg );
	}
	else
		$("#storeCodeErrorMsg").empty().append( "" );
	
	if(allowNext)
	{
		$.post(newURL, paramObj, function(data) {
	    	$( "#registerResult" ).empty().append( data );
	    	showPreloader(false);
	    	
	    	if(type == 'close')
	    		$("#btnContinue").empty().append(printBtn2);
	    	else
    		{
				$("#div-content").hide();
				$("#btnContinue").empty().append(toRegBtn);
    		}
	    });
	}
}

function goPrintRegister()
{
	$("#registerButton").hide();
	$("#div-content").hide();
	
	divPrint();
	
	$("#registerButton").show();
	$("#div-content").show();
}

var secCheck = false;
function gotoRegistrationNextStep(newURL)
{
	showPreloader(true);
	
	if(pageCtr == 2 && !isValidEmail)
	{
		validateEmail(true);
		return;
	}
	
	getFormValues();
	
	if(pageCtr == 4 && !secCheck)
	{
		showPreloader(false);
		return;
	}
		
	secCheck = false;
	if(!allowNext)
	{
		allowNext = true;
		showPreloader(false);
		return;
	}
	
	if(pageCtr == 8)
		pageCtr = 5;
	
	if(pageCtr < 6)
		pageCtr++;
	
	//pageCtr = 3;
	
	setPreviousClickable(pageCtr);
	
	var url = newURL + pageCtr + ".php";
	if(pageCtr == 6)
	{
		url = "registrationprintout.php";
		paramObj.r_code = $("#registerContent").find( 'input[name="reg_code"]' ).val();
		paramObj.r_date = $("#registerContent").find( 'input[name="reg_date"]' ).val();
		paramObj.r_fee = $("#registerContent").find( 'input[name="reg_fee"]' ).val();
		
		$.post(url, paramObj, function(data) {
        	$( "#regMainContainer" ).empty().append( data );
			
			divPrint();
	    });
	}
	
	if(pageCtr <= 5)
	{
		$("#imgStep"+ pageCtr).attr("src", "../images/reg_current_step.png");
		$("#imgStep" + (pageCtr - 1)).attr("src", "../images/reg_done_step.png");
		
		
		if(pageCtr == 5)
			$("#btnContinue").empty().append(printBtn);
		else 
			$("#btnContinue").empty().append(continueBtn);
	}
	
	if(pageCtr >= 4)
	{
		$.post(url, paramObj, function(data) {
        	$( "#registerContent" ).empty().append( data );
        	
        	var errorId = $("#registerContent").find( 'input[name="err_id"]' ).val();
        	if(errorId == -1)
    		{
        		pageCtr = 0;
        		$("#btnContinue").empty().append(backBtn);
    		}
        	
        	setFormValues();
        	
        	if(pageCtr == 4)
    		{
        		pParam = {};
        		pParam.runnerCnt = addRunnerCtr + 1;
        		$.post("paypalbutton.php", pParam, function(pData) {
        			$("#paypalPaymentDiv").empty().append(pData);
        		});
        		
        		$("#cashPaymentDiv").hide();
        		showPaypalDiv(true);
    		}
        	else
        		showPaypalDiv(false);
        	showPreloader(false);
	    });
		
		if(pageCtr == 7)
			pageCtr++;
	}
	else
	{
		$.post(url, paramObj, function(data) {
        	$( "#registerContent" ).empty().append( data );
        	setFormValues();
        	showPaypalDiv(false);
        	showPreloader(false);
	    });
		
		
	}
}

function setPreviousClickable(stepNum)
{
	if(stepNum > 0 && stepNum <= 5)
	{
		$("#imgStep" + stepNum).css('cursor', 'pointer');
		$("#imgStep" + stepNum).click(function(e){
			backToPreviousStep(stepNum, 'register');
		});
	}
}

function backToPreviousStep(stepNum, newURL)
{
	showPreloader(true);
	showPaypalDiv(false);
	if(pageCtr == stepNum)
		return;
	
	getFormValues();
	
	if(!allowNext)
	{
		allowNext = true;
		showPreloader(false);
		return;
	}
	
	pageCtr = stepNum;

	var url = newURL + pageCtr + ".php";
	$.post(url, paramObj, function(data){
    	$( "#registerContent" ).empty().append( data );
    	setFormValues();
    	
    	if(pageCtr == 5)
			$("#btnContinue").empty().append(printBtn);
		else 
			$("#btnContinue").empty().append(continueBtn);
    	
    	if(pageCtr == 4 && paramObj.payment_method == "PAYPAL")
		{
    		$("#cashPaymentDiv").hide();
    		showPaypalDiv(true);
		}
    	else
    		showPaypalDiv(false);
    	
    	showPreloader(false);
    });
}

function setFormValues()
{
	if(pageCtr == 2)
	{
//	    if(paramObj.r_country == null) {
//	    	$("#registerContent").find( 'select[name="country"] option[value="PH"]').attr('selected', "selected");
//	    }
	}
}

var isValidEmail = false;
function validateEmail(isNextPage)
{
	var vParams = {};
	vParams.v_check_email = true;
	vParams.v_method = "PARAMETER";
	vParams.v_table = "participant_info";
	vParams.v_column = "pi_email_add";
	vParams.v_value = $("#registerContent").find( 'input[name="emailAdd"]' ).val();
	$.post("validator.php", vParams, function(data){
		
		if(data == '')
		{
			isValidEmail = true;
			if(isNextPage)
				gotoRegistrationNextStep('register');
		}
		else 
		{
			if(data.search(/"Duplicate value"/i))
				$("#emailErrorMsg").empty().append( "This email address is already registered. You may login if your the owner." );
			else
				$("#emailErrorMsg").empty().append( data );
			
			showPreloader(false);
		}
	});
}

function getFormValues()
{
	if(pageCtr == 1)
	{
		paramObj.r_race_code = $("#registerContent").find( 'input[name="distance"]:checked').val();
		if(paramObj.r_race_code == null || paramObj.r_race_code == 0)
		{
			allowNext = false;
			alert("You need to select a run category.");
		}
	}
	else if(pageCtr == 2)
	{
		paramObj.r_code = "";
		paramObj.r_firstName = $("#registerContent").find( 'input[name="firstName"]' ).val();
		paramObj.r_lastName = $("#registerContent").find( 'input[name="lastName"]' ).val();
		paramObj.r_middle_ini = $("#registerContent").find( 'input[name="middleInitial"]' ).val();
		paramObj.r_gender = $("#registerContent").find( 'input[name="gender"]:checked' ).val();
		paramObj.r_birthdate = $("#registerContent").find( 'input[name="birthDate"]' ).val();
		paramObj.r_email = $("#registerContent").find( 'input[name="emailAdd"]' ).val();
		paramObj.r_mobile = $("#registerContent").find( 'input[name="mobileNo"]' ).val();
		paramObj.r_nationality = $("#registerContent").find( 'input[name="nationality"]' ).val();
		paramObj.r_country = $("#registerContent").find( 'select[name="country"]' ).val();
		paramObj.r_address1 = $("#registerContent").find( 'input[name="address1"]' ).val();
		paramObj.r_address2 = $("#registerContent").find( 'input[name="address2"]' ).val();
		paramObj.r_delivery_add = $("#registerContent").find( 'input[name="deliveryAdd"]:checked' ).val();
		paramObj.r_contact_name = $("#registerContent").find( 'input[name="cantactName"]' ).val();
		paramObj.r_contact_phone = $("#registerContent").find( 'input[name="contactPhone"]' ).val();
		
		if(paramObj.r_email == "")
		{
			allowNext = false;
			$("#emailErrorMsg").empty().append( requiredMsg );
		}
		else if(!isValidEmail)
			allowNext = false;
		else
			$("#emailErrorMsg").empty().append( "" );
		
		if(paramObj.r_firstName == "")
		{
			allowNext = false;
			$("#firstNameErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#firstNameErrorMsg").empty().append( "" );
		
		if(paramObj.r_lastName == "")
		{
			allowNext = false;
			$("#lastNameErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#lastNameErrorMsg").empty().append( "" );
		
		if(paramObj.r_gender == null)
		{
			allowNext = false;
			$("#genderErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#genderErrorMsg").empty().append( "" );
		
		if(paramObj.r_birthdate == "")
		{
			allowNext = false;
			$("#birthDateErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#birthDateErrorMsg").empty().append( "" );
		
		if(paramObj.r_address1 == "")
		{
			allowNext = false;
			$("#homeAddErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#homeAddErrorMsg").empty().append( "" );
		
		if(paramObj.r_delivery_add == "ADD2" && paramObj.r_address2 == "")
		{
			allowNext = false;
			$("#add2ErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#add2ErrorMsg").empty().append( "" );
		
		if(paramObj.r_country == "")
		{
			allowNext = false;
			$("#countryErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#countryErrorMsg").empty().append( "" );
		
		if(paramObj.r_nationality == "")
		{
			allowNext = false;
			$("#nationalityErrorMsg").empty().append( requiredMsg );
		}
		else
			$("#nationalityErrorMsg").empty().append( "" );
		
	}
	else if(pageCtr == 3)
	{
		paramObj.r_size = $("#registerContent").find( 'input[name="kitSize"]:checked' ).val();
		paramObj.r_color = $("#registerContent").find( 'input[name="kitColor"]:checked' ).val();
		paramObj.waiver_checked = $("#registerContent").find( 'input[name="waiverChecked"]:checked' ).val();
		paramObj.termsCondition_checked = $("#registerContent").find( 'input[name="termsConditionChecked"]:checked' ).val();
		
		/*paramObj.r_reg_outlet = $("#registerContent").find( 'input[name="regOutlet"]' ).val();*/
		paramObj.r_reg_cat = $("#registerContent").find( 'input[name="regCategory"]' ).val();
		paramObj.r_promo_no = $("#registerContent").find( 'input[name="promoNo"]' ).val();
		
		var sizeColorErrMsg = "";
		if(paramObj.r_size == null || paramObj.r_size == "" || paramObj.r_size == 0)
		{
			allowNext = false;
			sizeColorErrMsg = "You need to select a size.";
		}
		
		if(paramObj.r_color == null || paramObj.r_color == "" || paramObj.r_color == 0)
		{
			allowNext = false;
			if(sizeColorErrMsg != "")
				sizeColorErrMsg += "\n";
			
			sizeColorErrMsg += "You need to select a color.";
		}
		
		if(paramObj.waiver_checked == null || paramObj.waiver_checked == "")
		{
			allowNext = false;
			if(sizeColorErrMsg != "")
				sizeColorErrMsg += "\n";
			
			sizeColorErrMsg += "You need to agree on waiver of liability.";
		}
		
		if(paramObj.termsCondition_checked == null || paramObj.termsCondition_checked == "")
		{
			allowNext = false;
			if(sizeColorErrMsg != "")
				sizeColorErrMsg += "\n";
			
			sizeColorErrMsg += "You need to agree on the terms and conditions.";
		}
		
		if(addRunnerCtr > 0)
		{
			paramObj.withAddRunners = true;
			addRunnerInfos = new Array();
			addR = {};
			$(".dynaFormContent").each( function (index, formElem){
				
				addR = {};
				addR.r_firstName = $(formElem).find( 'input[name="firstName"]' ).val();
				addR.r_lastName = $(formElem).find( 'input[name="lastName"]' ).val();
				addR.r_mi = $(formElem).find( 'input[name="middleInitial"]' ).val();
				addR.r_category = $(formElem).find( 'select[name="arcategory"]' ).val();
				addR.r_size = $(formElem).find( 'select[name="arkitsize"]' ).val();
				addR.r_color = $(formElem).find( 'select[name="arkitcolor"]' ).val();
				
				if(addR.r_firstName == "" || addR.r_lastName == "")
				{
					allowNext == false;
					sizeColorErrMsg += "Incomplete information on additional runner/s.";
					return false;
				}
				
				addRunnerInfos.push(addR);
			});
			
			if(allowNext == true)
			{
				for (var s = 0; s <addRunnerInfos.length;s++)
				{
					addR = addRunnerInfos[s];
					$.post('saveaddrunner.php', addR, function(data){
						
					});
				}
			}
		}
		
		if(allowNext == false)
			alert(sizeColorErrMsg);
		
	}
	else if(pageCtr == 4)
	{
		paramObj.payment_method = $("#registerContent").find( 'input[name="paymentMethod"]:checked' ).val();
		if(paramObj.payment_method == "PAYPAL")
		{
			paramObj.r_reg_outlet = "CMROL999";
			allowNext = true;
			return;
		}
		
		if(secCheck == true)
		{
			allowNext = true;
			return;
		}
		
		paramObj.r_reg_outlet = $("#registerContent").find( 'input[name="securityCode"]' ).val();
		paramObj.r_bib = $("#registerContent").find( 'input[name="bibNumber"]' ).val();
		
		if(paramObj.r_reg_outlet == "")
		{
			allowNext = false;
			$("#regOutletErrorMsg").empty().append( requiredMsg );
		}
		else
		{
			allowNext = false;
			$("#regOutletErrorMsg").empty().append( "" );
			
			var vData = {};
			vData.v_table = "";
			vData.v_column = "";
			vData.v_value = paramObj.r_reg_outlet;
			vData.v_method = "SECURITY_CODE";
			
			$.post('validator.php', vData, function(data){
				if(data == "Valid security code"){
					pageCtr = 4;
					secCheck = true;
					gotoRegistrationNextStep('register');
				}
				else
				{
					pageCtr = 4;
					secCheck = false;
					showPreloader(false);
					$("#regOutletErrorMsg").empty().append( data );
				}
			});
		}
	}
}

function showPaypalDiv(isVisible)
{
	if(isVisible)
	{
		$("#registerButton").hide();
		$("#paypalPaymentDiv").show();
	}
	else
	{
		$("#registerButton").show();
		$("#paypalPaymentDiv").hide();
	}
}

function divPrint() 
{
    $("#regMainContainer").addClass("printable");
    window.print();
}

var addRunnerCtr = 0;
var addRunnerCtrName = 0;
function addRunner()
{
	if(addRunnerCtr >=20)
		alert("You can only add maximum of 20 runners for each transaction.");
		
	addRunnerCtr++;
	addRunnerCtrName++;
	$.post('addrunner.php?runner='+addRunnerCtrName, function(data){
		$("#addRunnerForm").append( data );
	});
}

function removeRunner(divID)
{
	if(addRunnerCtr == 1)
	{
		$("#addRunnerForm").empty();
		addRunnerCtr = 0;
		return;
	}
	
	$(divID).empty().remove();
	addRunnerCtr--;
}
